package ferp.android.activities.preferences;

import android.content.Context;
import android.content.res.Resources;
import android.preference.ListPreference;
import android.util.AttributeSet;
import android.view.View;
import ferp.android.GUI;

import java.util.ArrayList;

/**
 * User: olegs
 * Date: 8/17/12 9:25 AM
 */
public class List extends ListPreference
{
  public static <E extends Enum<E>> void setup(Preferences owner, int key, int resTypes, E selectedValue, Class<E> enumType, boolean enabled)
  {
    List preference = owner.find(List.class, key);

    preference.update(resTypes, selectedValue.ordinal(), enumType);
    preference.setEnabled(enabled);
  }

  public static void setup(Preferences owner, int key, boolean[] results, int resValues, int resDefault, boolean enabled)
  {
    List preference = owner.find(List.class, key);

    preference.update(results, resValues, resDefault);
    preference.setEnabled(enabled);
  }

  public static void setup(Preferences owner, int key, String summary)
  {
    List preference = owner.find(List.class, key);

    preference.setSummary(GUI.getColoredText("red", summary));
    preference.setEnabled(false);
  }

  public List(Context context)
  {
    this(context, null);
  }

  public List(Context context, AttributeSet attrs)
  {
    super(context, attrs);
  }

  public ArrayList<String> entriesToList()
  {
    CharSequence[] entries = getEntries();
    ArrayList<String> list = new ArrayList<String>(entries.length);

    for (CharSequence e : entries)
      list.add(e.toString());

    return list;
  }

  public <E extends Enum<E>> E update(int resTypes, int selected, Class<E> enumType)
  {
    setValueIndex(selected);
    setSummary(getContext().getResources().getStringArray(resTypes)[selected]);

    return Enum.valueOf(enumType, getValue());
  }

  public void update(boolean[] results, int resValues, int resDefault)
  {
    Resources r = getContext().getResources();

    String[] values = r.getStringArray(resValues);
    StringBuilder sb = new StringBuilder(256);

    sb.append(r.getString(resDefault));

    for (int i = 0; i < results.length; ++i)
      if (results[i])
        sb.append(", ").append(values[i]);

    setSummary(sb);
  }

  @Override
  protected void onBindView(View view)
  {
    super.onBindView(view);

    Preferences.initializePreferenceStyle(view, isEnabled());
  }

  @Override
  protected void onClick()
  {
    Preferences p = (Preferences)getContext();

    p.showDialog(Integer.valueOf(getKey()));
  }
}
